import { type OptionalFields } from '@gnlab/utils'
import { Steps, App } from 'antd'
import pick from 'lodash/pick'
import { flexCol } from '@/desktop/styles'
import { CoverPanel } from '@/desktop/views/app/cover-panel'
import { type AccountQywx } from '@/services/qywxs'
import { type Task, Target, saveTask } from '../logics'
import { ChooseQywxs } from './choose-qywxs'
import { ChooseTarget } from './choose-target'
import { SetContent } from './set-content'

export type Editing = Omit<OptionalFields<Task, 'id'>, 'status' | 'created' | 'externalWxids'> & {
  wxids: string[]
  qywxs: AccountQywx[] // ChooseQywxs 附带的企微信息列表
}

export const defaults: Editing = {
  name: '',
  wxids: [],
  qywxs: [],
  targetType: Target.标签客户,
  tagIds: [],
  contacts: [],
  startAt: null,
  content: [],
  delay: 1,
}

const steps = [
  { key: 'qywxs', title: '选择企微' },
  { key: 'target', title: '选择群发对象' },
  { key: 'content', title: '设置群发内容' },
]

export function Edit({ task, onClose }: { task: Task | true; onClose: () => void }) {
  const { message, modal } = App.useApp()
  const [step, setStep] = useState(0)

  function confirmClose() {
    modal.confirm({
      title: '确定离开此页面吗？',
      content: '任务内容将不会被保存。',
      onOk: onClose,
    })
  }

  const [editing, setEditing] = useState<Editing>(() =>
    task === true ? { ...defaults } : { ...task, wxids: task.externalWxids, qywxs: [] },
  )
  function goPrev(updates?: Partial<Editing>) {
    if (updates) setEditing(editing => ({ ...editing, ...updates }))
    setStep(step => (step === 0 ? 0 : step - 1))
  }
  async function goNext(updates: Partial<Editing>) {
    const updated = { ...editing, ...updates }
    setEditing(updated)
    if (step < 2) setStep(step + 1)
    else return submit(updated) // 手动传入更新后的值，以保证是最新的，因为 setEditing() 并不会实时改变 editing
  }
  async function submit(editing: Editing) {
    const data = {
      ...pick(task === true ? {} : task, 'id', 'status'),
      ...editing,
      externalWxids:
        editing.targetType === Target.全部客户 || editing.targetType === Target.标签客户
          ? editing.wxids
          : [],
    }
    const res = await saveTask(data)
    if (res.success) {
      void message.success('任务保存成功')
      onClose()
    } else {
      void message.error('任务保存失败：' + res.error)
    }
  }

  return <CoverPanel
    title={task === true ? '创建群发任务' : '编辑群发任务 #' + task.id}
    onClose={confirmClose}
  >
    <div css={s.wrap}>
      <Steps current={step} items={steps} />
      <main>
        {step === 0 ? (
          <ChooseQywxs wxids={editing.wxids} goNext={goNext} onClose={onClose} />
        ) : null}
        {step === 1 ? <ChooseTarget editing={editing} goNext={goNext} goPrev={goPrev} /> : null}
        {step === 2 ? <SetContent editing={editing} goNext={goNext} goPrev={goPrev} /> : null}
      </main>
    </div>
  </CoverPanel>
}

const s = {
  wrap: css`
    ${flexCol};
    flex: 1;
    min-height: 300px;
    padding-top: 20px;
    & > main {
      flex: 1;
      overflow: hidden;
    }
  `,
}
